import { createContext, useEffect, useState } from "react";
import useAuthButtons from "@/hooks/useAuthButtons";

import TableData from "./TableData";
import SearchForm from "./SearchForm";
import { Params, RecordItem, SearchParam, SelectOptions } from "./type";
import request from "@/utils/request";
import { useAppSelector } from "@/utils/hooks";

export const Context = createContext({ total: 0 });

const UserManage = () => {
	const [app] = useAppSelector(state => [state.app]);
	const [data, setData] = useState<RecordItem[]>([]);
	const [total, setTotal] = useState(0);
	const [termIdSelectOptions, setTermIdSelectOptions] = useState<[]>();
	const [classifySelectOptions, setClassifySelectOptions] = useState<[]>();
	const [searchParam, setSearchParam] = useState<SearchParam>();
	const [filterData, setFilterData] = useState<Params>({
		page: 1,
		pageSize: 10
	});
	//
	const queryTermOptions = () => {
		// 管理员详情接口
		request("courseManageQueryTermOptions", { data: {} }).then(res => {
			if (res.code === 0 && res.data) {
				setTermIdSelectOptions(res.data);
			}
		});
	};

	const queryClassifyOptions = () => {
		// 管理员详情接口
		request("courseManageQueryClassifyOptions", { data: {} }).then(res => {
			if (res.code === 0 && res.data) {
				setClassifySelectOptions(res.data);
			}
		});
	};

	useEffect(() => {
		queryTermOptions();
		queryClassifyOptions();
		doSearch({});
	}, []);

	const doSearch = (params: object) => {
		request("courseManageList", {
			data: {
				...filterData,
				...params,
				tenantId: app.currentEntity.entityId
			}
		}).then(res => {
			if (res?.code === 0) {
				setFilterData({ ...filterData, ...params });
				setData(res.data.list || []);
				setTotal(res.data.total);
			}
		});
	};

	const handlePageChange = (page: number, pageSize?: number) => {
		doSearch({ searchParam: searchParam, page: page, pageSize: pageSize || 10 });
	};

	const handleSearch = (searchParam: SearchParam) => {
		doSearch({ ...searchParam, page: 1, pageSize: 10 });
		setSearchParam(searchParam);
	};

	// 按钮权限
	const { BUTTONS } = useAuthButtons();
	// console.log(BUTTONS.add);

	return (
		<div className="card content-box">
			<Context.Provider value={{ total }}>
				<SearchForm doSearch={handleSearch} options={{ term: termIdSelectOptions, classify: classifySelectOptions }} />
				<TableData
					options={{ term: termIdSelectOptions, classify: classifySelectOptions }}
					filterData={filterData}
					data={data}
					page={filterData.page}
					doSearch={doSearch}
					pageSize={filterData.pageSize}
					onPageChange={handlePageChange}
					total={total}
				></TableData>
			</Context.Provider>
		</div>
	);
};

export default UserManage;
